package com.cl.unipay4j.wx.pay;

import com.cl.unipay4j.core.*;
import com.cl.unipay4j.core.pay.INotify;
import com.cl.unipay4j.core.util.RequestUtil;
import com.cl.unipay4j.wx.AbstractWxPay;
import com.cl.unipay4j.wx.sdk.WXPayConstants;
import com.cl.unipay4j.wx.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @ClassName AliPayNotify
 * @Description 微信支付回调
 * @Author Small
 * @Date 2020/4/26 11:54
 * @Version 1.0
 **/
@Slf4j
public class WxPayNotify extends AbstractWxPay implements INotify {

    public WxPayNotify() {
        super();
    }

    public WxPayNotify(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 方法描述: 支付回调
     * @Author Small
     * @param request
     * @Date 2019/12/4 14:58
     * @return com.weixing.mall.pay.NotifyResult
     */
    @Override
    public Result execNotify(HttpServletRequest request) {
        try {
            String xmlStr = RequestUtil.getStrFromInputSteam(request.getInputStream());
            Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
            // 验签
            if (WXPayUtil.isSignatureValid(map, wxPayConfig.getKey(), wxPayConfig.getContext().getSignType())) {
                String returnCode = map.get(WXPayConstants.RETURN_CODE);
                if (UnipayConst.SUCCESS.equals(returnCode)) {
                    if (UnipayConst.SUCCESS.equals(map.get(WXPayConstants.RESULT_CODE))) {
                        return Result.tradeSuccess(wrapperPayResponse(map));
                    } else {
                        return Result.tradeFail(TradeStateEnum.FAIL.getValue(), map.get(WXPayConstants.ERR_CODE), map.get(WXPayConstants.ERR_CODE_DES));
                    }
                } else {
                    // 通信失败
                    return Result.returnFail(returnCode, map.get(WXPayConstants.RETURN_MSG));
                }

            } else {
                Result.invalidSign();
            }
            // 解析微信回调参数
        } catch (Exception e) {
            log.warn("WxNotify::=> 回调时发生异常", e);
        }
        return Result.exception();
    }

    /**
     * 回调成功，同步返回给支付平台的报文
     * @return
     */
    @Override
    public String successMsg() {
        return "<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>";
    }

    /**
     * 回调失败，同步返回给支付平台的报文
     * @return
     */
    @Override
    public String failMsg() {
        return "<xml> <return_code><![CDATA[FAIL]]></return_code> <return_msg><![CDATA[ERROR]]></return_msg> </xml>";
    }

}
